package com.xian.im.modules.sensitive.filter;

import com.xian.im.common.constant.ThreadLocalConstant;
import com.xian.im.common.proto.MsgRequest;
import com.xian.im.common.utils.sys.ThreadLocalUtil;
import com.xian.im.modules.sensitive.SensitiveBloomFactory;
import com.xian.im.modules.sensitive.handler.SensitiveBloom;
import com.xian.im.modules.sensitive.service.RedisService;
import com.xian.im.modules.sensitive.SensitiveWordMessageFilter;
import lombok.extern.slf4j.Slf4j;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.List;

import static com.xian.im.modules.avchat.IMCoreHandlerContext.replace;

/**
 * @program: xian-code
 * @description:  默认敏感词过滤
 * @author: liru.xian
 * @create: 2021-01-21 15:29
 **/
@Slf4j
@Component
public class DefaultSensitiveWordMessageFilter implements SensitiveWordMessageFilter {

    private final RedisService redisService;

    public DefaultSensitiveWordMessageFilter(RedisService redisService) {
        this.redisService = redisService;
    }

    /**
     * 执行消息体过滤
     *
     * @param message
     * @return
     */
    @Override
    public Boolean doFilter(MsgRequest message) {
        //  敏感词  redis 布隆
        if(message.getBody() == null){
            return Boolean.TRUE;
        }
        String s = message.getBody().toString();
        if(StringUtils.isBlank(s)){
            return Boolean.TRUE;
        }
        //中文分词
        List<Term> cut = ToAnalysis.parse(s).getTerms();
        List<String> sensitiveList = new ArrayList<>();
        for (Term s1 : cut) {
            Boolean aBoolean = SensitiveBloomFactory.type(SensitiveBloom.GUAVA_TYPE).includeByBloomFilter(s1.getName());
            if(aBoolean){
                sensitiveList.add(s1.getName());
            }
        }
        if(sensitiveList.isEmpty()){
            return Boolean.TRUE;
        }else {
            ThreadLocalUtil.set(ThreadLocalConstant.NT, sensitiveList);
            for (String nt : sensitiveList) {
                String replace = replace(nt.length());
                s = s.replace(nt,replace);
            }
            message.setBody(s);
            return Boolean.FALSE;
        }
    }



}
